package com.um.pasantiaum.objetos;

import java.util.ArrayList;
import java.util.List;

import android.util.Log;

import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;

public class CamionManager {

	private static CamionManager sCamionManager;
	private ArrayList<Camion> mCamiones;
	private static ParseUser sCurrentUser;

	public static CamionManager getCamionManager(ParseUser currentUser) {
		if (sCamionManager == null || !currentUser.equals(sCurrentUser))
			sCamionManager = new CamionManager(currentUser);
		return sCamionManager;
	}

	private CamionManager(ParseUser currentUser) {

		mCamiones = new ArrayList<Camion>();
		sCurrentUser = currentUser;

		ParseQuery<ParseObject> query = ParseQuery.getQuery("Truck");
		query.whereEqualTo("empresa", sCurrentUser);
		query.whereEqualTo("isInStock", true);
		query.include("truck");

		try {
			List<ParseObject> objects = query.find();

			for (ParseObject po : objects) {
				ParseUser temp = po.getParseUser("truck");
				mCamiones.add(new Camion(temp));
			}

		} catch (ParseException e1) {
			Log.d("Camiones", "Error: " + e1.getMessage());
		}
	}

	public ArrayList<Camion> getCamiones() {
		return mCamiones;
	}

	public void addCamion(ParseUser camion) {
		mCamiones.add(new Camion(camion));
	}

	public void removeCamion(Camion camion) {
		if (camion != null) {

			ParseQuery<ParseUser> userQuery = ParseUser.getQuery();

			userQuery.getInBackground(camion.getUserId(),
					new GetCallback<ParseUser>() {

						@Override
						public void done(ParseUser object, ParseException e) {
							if (e == null) {
								ParseQuery<ParseObject> query = ParseQuery
										.getQuery("Truck");

								query.whereEqualTo("truck", object);

								ParseObject aux;
								try {
									aux = query.getFirst();
									aux.put("isInStock", false);
									aux.saveInBackground();
								} catch (ParseException e1) {
									Log.d("User", "Error: " + e1.getMessage());
								}
							} else {
								Log.d("User", "Error: " + e.getMessage());
							}

						}
					});
			mCamiones.remove(camion);
		}

	}

}
